from flask import jsonify, request, session
from myApp.model.user_model import User
from flask import Blueprint
from functools import wraps
import hashlib

# from myApp.utils.InitModel import run

user_db = Blueprint('user', __name__)


# 注册
def register(data) -> User:
    account = data.get('account')
    password = data.get('password')
    role = "user"
    nickname = "Me"
    ent_user_id = data.get('ent_user_id')

    # 1. 校验账户是否存在
    user = User.get_user_by_account(account)
    if user:
        return jsonify({'message': '账户已存在'}), 202

    # 2. 密码加密
    password = hash_password(password)

    # 3. 创建用户
    user = User.create_user(nickname, account, password, role, ent_user_id)
    print(user.serialize())
    return user


# 登录
@user_db.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    account = data.get('account')
    password = data.get('password')

    # 1. 校验账户是否存在, 不存在注册
    user = User.get_user_by_account(account)

    if not user:
        new_user = register(data)
        return jsonify({'message': 'success', 'user_info': new_user.serialize()}), 200

    # 2. 校验密码
    if not check_password(password, user.password):
        return jsonify({'message': '密码错误'}), 202
    # 将id转为字符串
    return jsonify({'message': 'success', 'user_info': user.serialize()}), 200


# 根据ent_user_id登录
@user_db.route('/login/ent', methods=['POST'])
def login_by_ent_user_id():
    data = request.get_json()
    ent_user_id = data.get('ent_user_id')
    # 1. 校验账户是否存在
    user = User.get_user_by_ent_user_id(ent_user_id)
    if not user:
        return jsonify({'message': '账户不存在'}), 202
    return jsonify({'message': 'success', 'user_info': user.serialize()}), 200


# @user_db.route('/logout')
# def logout():
#     # 登出时移除会话中的用户标识符
#     session.pop('user', None)
#     return jsonify({'message': 'success'}), 200


# @user_db.route('/user/info')
# def user_info():
#     user = session.get('user')
#     if user:
#         return jsonify({'message': 'success', 'user': user}), 200
#     else:
#         return jsonify({'message': '未登录'}), 202


def hash_password(password):
    hashed_password = hashlib.md5((password).encode()).hexdigest()
    return hashed_password


def check_password(password, hashed_password):
    return hashed_password == hash_password(password)

# 自定义装饰器来验证用户是否登录
# def login_required(f):
#     @wraps(f)
#     def decorated_function(*args, **kwargs):
#         # 检查会话中是否存在用户信息
#         if 'user' not in session:
#             # 如果用户未登录，返回未授权的消息
#             return jsonify({'message': '未登录'}), 401
#         return f(*args, **kwargs)
#
#     return decorated_function
